// pages/fabu/fabu.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    selectImages:[
    ],
    uploadImgs:[],
    type: [
    {name: "寻物启事",id: 0},
    {name: "失物招领",id: 1},
  ],
  categorys: [
    { id: 2, content: '身份证' },
    { id: 3, content: '学生证' },
    { id: 4, content: '饭卡' },
    { id: 5, content: '雨伞' },
    { id: 6, content: '书籍' },
    { id: 7, content: '水杯' },
    { id: 8, content: '衣服' },
    { id: 9, content: '其他' }
  ],
  categoryInd: 0, //物品类别
  typeId: 0, //发布类型
  },
  onShow(){

  },
//选择图片
chooseImage() {
  if (this.data.selectImages.length < 9) {
    wx.chooseImage({
      count:9,
      success: (res) => {
        this.setData({
          selectImages: this.data.selectImages.concat(res.tempFilePaths)
        })
      }
    })
  } else {
    wx.showToast({
      title: '最多上传九张图片',
      icon: 'loading',
      duration: 3000
    });
  }
},

// 删除图片
deleteImg: function (e) {
  var imgs = this.data.selectImages;
  var index = e.currentTarget.dataset.index;
  imgs.splice(index, 1);
  this.setData({
    selectImages: imgs
  });
},
//发布执行
submit(e){
  let phone = e.detail.value.phone
  if(!this.ValidatePhone(phone)){
    wx.showToast({
      title: '手机号有误！',
      icon: 'error'
    })
    return 
  }
  this.uploadImages().then(res => {
    let date = new Date()
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    let dateFormat = y+'-'+m+'-'+d
    //保存数据接口
    wx.cloud.database().collection('lostItem').add({
      data:{
        date: dateFormat,
        title : e.detail.value.title,
        place : e.detail.value.place,
        typeId : this.data.typeId,
        typeName: this.data.type[this.data.typeId].name,
        phone : phone,
        describe :e.detail.value.describe,
        images:this.data.uploadImgs,
        status: '待解决',
        categoryName : this.data.categorys[e.detail.value.categoryInd].content,
        categoryId : this.data.categorys[e.detail.value.categoryInd].id,
      },
      success: res => {
        if(res){
          console.log('保存成功')
        }
        wx.navigateBack({
          delta: 2,
        })
      }

    })
  })
 
},
 //上传图片到云存储,异步函数，防止图片还没上传，就执行插入云数据库
 uploadImages() {
  let _this = this
  return new Promise(function (resolve, reject) {
    function upload(index) {
      var picnum = index+1
      wx.showLoading({
        title: '上传第' + picnum + '张图片'
      })
      console.log(_this.data.selectImages)
      wx.cloud.uploadFile({
        cloudPath: 'itemImgs/' + new Date().getTime() + '_' + Math.floor(Math.random() * 1000) + '.jpg', //给图片命名
        filePath: _this.data.selectImages[index], //本地图片路径
        success: (res) => {
          _this.data.uploadImgs[index] = res.fileID
          wx.hideLoading({
            success: (res) => {},
          })
          //判断是否全部上传
          if (_this.data.selectImages.length - 1 <= index) {
            console.log('已全部上传')
            resolve('success')
            return
          } else {
            upload(index + 1)
          }
        },
        fail: (err) => {
          reject('error')
          wx.showToast({
            title: '上传失败，请重新上传',
            type: 'none'
          })
        }
      })
    }
    upload(0)
  })
},
/**
   * 发布类型
   */
  type(e) {
    this.setData({
      typeId: this.data.type[e.detail.value].id
    })
  },
  category(e){
    this.setData({
      categoryInd: e.detail.value
    })
  },
    //校验手机号
    ValidatePhone(val) {
      var isPhone = /^(0|86|17951)?(13[0-9]|15[012356789]|18[0-9]|14[57]|17[678])[0-9]{8}$/ //手机号码
      if (isPhone.test(val)) {
        return true;
      } else {
        return false;
      }
    },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
  }
})